﻿using Manox.Libs.ODB;
using System;
using System.Collections.Generic;
using UnityEngine;

namespace Manox.Libs.MVC
{
    public class ControllersManager : MonoBehaviour
    {
        /// <summary>Objects.</summary>
        public SortedDictionary<Guid, GameObject> Objects;
        /// <summary>Views object.</summary>
        public GameObject ControllersObject;

        /// <summary>
        /// Start.
        /// </summary>
        public void Start()
        {
            this.Objects = new SortedDictionary<Guid, GameObject>();

            ObjectDatabaseManager odb = this.GetComponent<ObjectDatabaseManager>();

            odb.ItemAdded += this.OdbItemAdded;
        }

        /// <summary>
        /// Odb item added.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="eventArgs"></param>
        private void OdbItemAdded(object sender, ItemAddedEventArgs eventArgs)
        {
            if (eventArgs.NewItem is Model)
            {
                GameObject viewResource = Resources.Load<GameObject>(
                    (eventArgs.NewItem as Model).ViewResourceName.Get());

                if (viewResource != null)
                {
                    GameObject objectInstance = GameObject.Instantiate(viewResource);

                    objectInstance.transform.parent = this.ControllersObject.transform;
                    objectInstance.GetComponent<ViewBase>().SetData(eventArgs.NewItem as Model);

                    this.Objects.Add(eventArgs.NewItem.Id, objectInstance);
                }
            }
        }
    }
}